package com.sh.personnel.security;

import com.sh.personnel.domain.ITbUser;
import com.sh.personnel.mapper.IPermissionMapper;
import com.sh.personnel.mapper.IRoleMapper;
import com.sh.personnel.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.List;

/**
 * @author 林思浩
 * @date 2020/02/26 21:31
 */
@Service
public class IUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    IUserMapper userMapper;

    @Autowired
    IPermissionMapper permissionMapper;

    @Autowired
    IRoleMapper roleMapper;

    /**
     * 用户密码登录
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ITbUser user = userMapper.findUserByUsername(username);
        if(ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<String> permissions = permissionMapper.findPermissionByUserId(user.getId());
        List<String> roles = roleMapper.findRoleByUserId(user.getId());
        permissions.addAll(roles);
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        ISecurityUser securityUser = new ISecurityUser(user.getId(), user.getUsername(), user.getPassword(), authorities);
        return securityUser;
    }

}
